package de.gwtprime.server.model;

import java.util.logging.Logger;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.google.web.bindery.requestfactory.server.RequestFactoryServlet;

import de.gwtprime.server.sql.helper.HibernateHelper;
import de.gwtprime.shared.VoteType;



@Entity
@Table(name = "vote")
public class Vote extends AbstractVote {
	
	/**
	 * SerialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(Vote.class.getName());
	
	private ArticleSection articleSection;
	
	@ManyToOne
	@JoinColumn
	public ArticleSection getArticleSection() {
		return articleSection;
	}

	public void setArticleSection(ArticleSection section) {
		this.articleSection = section;
	}
	
	public void remove(){
		long id = getArticleSection().getId();
		super.remove();
		HibernateHelper.find(ArticleSection.class, id).decreaseVoteValueAndPersist();
	}
	
	
	@ManyToOne
	@JoinColumn
	public User2 getUser() {
		return user;
	}

	public void setUser(User2 user) {
		this.user = user;
	}
	
	
	public Long getTest() {
		if(articleSection == null)
			return 0l;
		return articleSection.getId();
	}

	public void setTest(Long test) {
		this.test = test;
	}


	private Long test = 0l;
	

	public void setType(VoteType type) {
		this.type = type;
	}
	
	
	public void addVote(Long articleSectionId){
		addVote(articleSectionId, null);
	}
	
	
	public void addVote(Long articleSectionId, User2 user){
		
		logger.info(String.format("Adding vote to DB, type = '%s', articleId = '%s'", getType(), articleSectionId));
		
		ArticleSection section = HibernateHelper.find(ArticleSection.class, articleSectionId);
		setArticleSection(section);

		if(user==null){
			try{
				user = (User2)RequestFactoryServlet.getThreadLocalRequest().getSession().getAttribute("user");
			}catch(Exception e){

			}
		}

		logger.info("user from the session "+user.getEmail()+", id: "+user.getId());
		
		setUser(user);
		
		section.addVote(this);
		section.persist();
		
	}
	
}
